/* ------------------------------------------------------------------------*
 *
 * ------------------------------------------------------------------------*/
#include "bsp.h"
#include "bsp_spim.h"
#include "stdint.h"
#include "os_obj.h"
#include "systask.h"

#include "nor_cmd.h"
#include "extblockflashlog.h"

#include "str_ext.h"
#include "common.h"

/*****************************************************************************
* @brief   extern .
*****************************************************************************/
extern const log_buff_cfg_type  log_buff_cfg;

/*****************************************************************************
* @brief   sim flash define .
*****************************************************************************/
#define SIM_NAND_ADDR			(0x800000)
#define PAGE_SIZE				0x800
#define PAGE_PER_BLOCK			16
#define LOG_SIZE				48

/*****************************************************************************
* @brief   hal .
*****************************************************************************/
void BLogErase(uint32_t block);             /*从指定地址擦除，Nums指定擦除的扇区个数*/
void BLogProgram(uint32_t block); /*向指定指定地址编程数据*/
void BLogRead(uint32_t page, uint16_t offset, uint16_t Len, uint8_t *Data);    /*读取块数据*/

/*****************************************************************************
* @brief   config .
*****************************************************************************/
block_log_info_type blog_info;
const block_log_cfg_type blog_cfg = 
{
	.block_base = 0,
	.block_amount = 16,
	.page_per_block = PAGE_PER_BLOCK,
	.page_size = PAGE_SIZE,
	.log_size = LOG_SIZE,
	.Info = &blog_info,
	.Erase = BLogErase,
	.Program  = BLogProgram,
	.Read = BLogRead,
};

/*--------------------------------------------------------------------------------*
* log buff hal
*---------------------------------------------------------------------------------*/
void BLogProgram(uint32_t block)
{
	uint32_t base = SIM_NAND_ADDR + block * PAGE_PER_BLOCK * PAGE_SIZE;
	
	BLogErase(block);
	bsp_spim_write(base, PAGE_PER_BLOCK * PAGE_SIZE, (void *)(log_buff_cfg.info->flash_base));
}

void BLogRead(uint32_t page, uint16_t offset, uint16_t Len, uint8_t *Data)
{
	uint32_t base = SIM_NAND_ADDR + page * PAGE_SIZE + offset;

	bsp_spim_read(base, Len, Data);
}

void BLogErase(uint32_t block)
{
	uint32_t amount = PAGE_PER_BLOCK * PAGE_SIZE / 4096;
	uint32_t index;
	uint32_t base = SIM_NAND_ADDR + block * PAGE_PER_BLOCK * PAGE_SIZE;
	
	for(index=0; index < amount; index++)
	{
		bsp_spim_erase(base + index * 4096);
	}

}
